"""
RestFul API JSON
"""
import contextlib

from starlette.applications import Starlette

from injection_service.restful.common import get_config
from injection_service.restful.exception import exception_handlers
from injection_service.restful.middleware import middleware
from injection_service.restful.models import Base
from injection_service.restful.models import get_engine_session
from injection_service.restful.routes import routes


engine, async_session = get_engine_session(get_config("DATABASE_URL"))


@contextlib.asynccontextmanager
async def lifespan(app):
    async with async_session() as session:
        app.state.db = session
        yield app.state.db


async def on_start():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)


async def on_shutdown():
    await engine.dispose()


app = Starlette(routes=routes, lifespan=lifespan,
                middleware=middleware, exception_handlers=exception_handlers)


if __name__ == '__main__':
    import uvicorn

    uvicorn.run("__init__:app", port=8080, reload=True)
